/**	
 * <br>
 * Copyright 2011 Chuan. All rights reserved.<br>
 * <br>			 
 * Package: com.chuan.mantu.extend <br>
 * FileName: HttpMultipartPostAsyncTask.java <br>
 * <br>
 * @version
 * @author javacyc@qq.com
 * @created 2012-11-27
 * @last Modified 
 * @history
 */

package com.chuan.mantu.extend;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.chuan.mantu.R;
import com.chuan.mantu.UploadActivity;
import com.chuan.mantu.utils.Const;
import com.chuan.mantu.utils.FileUtil;

/**
 * {实现文件上传进度条}
 * 
 * @author javacyc@qq.com
 * @created 2012-11-27 下午02:31:36
 * @lastModified
 * @history
 */

public class HttpMultipartPostAsyncTask extends AsyncTask<String, Integer, String> {

	ProgressDialog pd;
	long totalSize;
	Context context;
	String picFilePath;
	String picCategory;

	public HttpMultipartPostAsyncTask(Context context, String picFilePath, String picCategory) {
		this.context = context;
		this.picFilePath = picFilePath;
		this.picCategory = picCategory;
	}

	@Override
	protected void onPreExecute() {
		pd = new ProgressDialog(context);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage(context.getString(R.string.httppost_task_1));
		pd.setCancelable(false);
		pd.show();
	}

	@Override
	protected String doInBackground(String... arg0) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = UUID.randomUUID().toString(); //边界标示，随即生成
		try {
			URL url = new URL(Const.UPLOAD_URL);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			con.setRequestProperty("Pictype", picCategory);//额外参数传递
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data;" + "name=\"file1\";filename=\"" + FileUtil.getFileName(picFilePath) + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			File file = new File(picFilePath);
			totalSize = file.length();
			FileInputStream fStream = new FileInputStream(file);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			int uploadedSize = 0;
			pd.setMax((int)totalSize);
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
				uploadedSize += length;
				pd.setProgress(uploadedSize);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 将Response显示于Dialog */
			/* 关闭DataOutputStream */
			ds.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(String ui) {
		// 文件上传后的操作
		pd.dismiss();
		UploadActivity uploadActivity = (UploadActivity)context;
		uploadActivity.uploadSuccess();
	}
}
